using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.Material;

namespace WPF_MVVM_Test.Services.Material
{
    /// <summary>
    /// 物料服务类
    /// </summary>
    public class MaterialService
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl = "http://8.140.242.140:8888/api/Material";

        public MaterialService()
        {
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 获取物料列表
        /// </summary>
        /// <param name="categoryId">分类编号</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns></returns>
        public async Task<MaterialApiResponse> GetMaterialsByCategoryAsync(string categoryId = "", int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                var url = $"{_baseUrl}/GetMaterialsByCategory?pageIndex={pageIndex}&pageSize={pageSize}";
                if (!string.IsNullOrEmpty(categoryId))
                {
                    url += $"&categoryId={categoryId}";
                }

                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };
                    
                    var result = JsonSerializer.Deserialize<MaterialApiResponse>(jsonString, options);
                    return result ?? new MaterialApiResponse();
                }
                else
                {
                    return new MaterialApiResponse
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                return new MaterialApiResponse
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 根据ID获取物料详情
        /// </summary>
        /// <param name="materialId">物料ID</param>
        /// <returns></returns>
        public async Task<MVVM_Model.Material.Material?> GetMaterialByIdAsync(string materialId)
        {
            try
            {
                var url = $"{_baseUrl}/GetMaterialById?id={materialId}";
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };
                    
                    var result = JsonSerializer.Deserialize<MVVM_Model.Material.Material>(jsonString, options);
                    return result;
                }
                
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 新增物料
        /// </summary>
        /// <param name="material">物料信息</param>
        /// <returns></returns>
        public async Task<MaterialApiResponse> AddMaterialAsync(MVVM_Model.Material.Material material)
        {
            try
            {
                var url = $"{_baseUrl}/AddMaterial";
                
                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                };
                
                var jsonString = JsonSerializer.Serialize(material, options);
                var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PostAsync(url, content);
                
                if (response.IsSuccessStatusCode)
                {
                    var responseContent = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<MaterialApiResponse>(responseContent, options);
                    return result ?? new MaterialApiResponse { IsSuc = true, Code = 200, Msg = "操作成功" };
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    return new MaterialApiResponse
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {errorContent}"
                    };
                }
            }
            catch (Exception ex)
            {
                return new MaterialApiResponse
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 更新物料信息
        /// </summary>
        /// <param name="material">物料信息</param>
        /// <returns></returns>
        public async Task<bool> UpdateMaterialAsync(MVVM_Model.Material.Material material)
        {
            try
            {
                var url = $"{_baseUrl}/UpdateMaterial";
                
                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                };
                
                var jsonString = JsonSerializer.Serialize(material, options);
                var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PutAsync(url, content);
                return response.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 获取物料分类树形结构
        /// </summary>
        /// <returns></returns>
        public async Task<MaterialCategoryResponse> GetMaterialCategoryTreeAsync()
        {
            try
            {
                var url = $"{_baseUrl}/GetMaterialCategoryTree";
                var response = await _httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };
                    
                    var apiResult = JsonSerializer.Deserialize<MaterialCategoryApiResponse>(jsonString, options);
                    
                    if (apiResult != null && apiResult.IsSuc)
                    {
                        // 将DTO转换为Model
                        var convertedData = ConvertDtoToModel(apiResult.Data);
                        
                        return new MaterialCategoryResponse
                        {
                            IsSuc = apiResult.IsSuc,
                            Code = apiResult.Code,
                            Msg = apiResult.Msg,
                            Data = convertedData
                        };
                    }
                    
                    return new MaterialCategoryResponse
                    {
                        IsSuc = false,
                        Code = 500,
                        Msg = "数据转换失败"
                    };
                }
                else
                {
                    return new MaterialCategoryResponse
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.StatusCode}"
                    };
                }
            }
            catch (Exception ex)
            {
                return new MaterialCategoryResponse
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 将DTO转换为Model
        /// </summary>
        /// <param name="dtoList"></param>
        /// <returns></returns>
        private List<MaterialCategory> ConvertDtoToModel(List<MaterialCategoryTreeDto> dtoList)
        {
            var result = new List<MaterialCategory>();
            
            if (dtoList == null)
            {
                System.Diagnostics.Debug.WriteLine("ConvertDtoToModel: dtoList is null");
                return result;
            }
            
            System.Diagnostics.Debug.WriteLine($"ConvertDtoToModel: Converting {dtoList.Count} items");
            
            foreach (var dto in dtoList)
            {
                System.Diagnostics.Debug.WriteLine($"Converting DTO: {dto.Name} (ID: {dto.Id})");
                
                var category = new MaterialCategory
                {
                    Id = dto.Id.ToString(),
                    CategoryName = dto.Name,
                    ParentId = dto.ParentId?.ToString() ?? string.Empty,
                    Level = 0, // 层级会在UI层设置
                    Children = ConvertDtoToModel(dto.Children)
                };
                
                System.Diagnostics.Debug.WriteLine($"Converted to Model: {category.CategoryName} (ID: {category.Id})");
                result.Add(category);
            }
            
            System.Diagnostics.Debug.WriteLine($"ConvertDtoToModel: Converted {result.Count} items");
            return result;
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }

    /// <summary>
    /// 物料API响应模型
    /// </summary>
    public class MaterialApiResponse
    {
        public bool IsSuc { get; set; }
        public int Code { get; set; }
        public string Msg { get; set; } = string.Empty;
        public MaterialPagedData Data { get; set; } = new MaterialPagedData();
    }

    /// <summary>
    /// 物料分页数据
    /// </summary>
    public class MaterialPagedData
    {
        public List<MVVM_Model.Material.Material> Data { get; set; } = new List<MVVM_Model.Material.Material>();
        public int TotalCount { get; set; }
        public int TotalPage { get; set; }
    }

    /// <summary>
    /// 物料分类API响应模型（原始DTO）
    /// </summary>
    public class MaterialCategoryApiResponse
    {
        public bool IsSuc { get; set; }
        public int Code { get; set; }
        public string Msg { get; set; } = string.Empty;
        public List<MaterialCategoryTreeDto> Data { get; set; } = new List<MaterialCategoryTreeDto>();
    }

    /// <summary>
    /// 物料分类响应模型（转换后的Model）
    /// </summary>
    public class MaterialCategoryResponse
    {
        public bool IsSuc { get; set; }
        public int Code { get; set; }
        public string Msg { get; set; } = string.Empty;
        public List<MaterialCategory> Data { get; set; } = new List<MaterialCategory>();
    }

    /// <summary>
    /// 物料分类树形结构DTO（匹配后台返回）
    /// </summary>
    public class MaterialCategoryTreeDto
    {
        /// <summary>
        /// 分类ID
        /// </summary>
        public Guid Id { get; set; }

        /// <summary>
        /// 分类名称
        /// </summary>
        public string Name { get; set; } = string.Empty;

        /// <summary>
        /// 父级分类ID
        /// </summary>
        public Guid? ParentId { get; set; }

        /// <summary>
        /// 子分类
        /// </summary>
        public List<MaterialCategoryTreeDto> Children { get; set; } = new List<MaterialCategoryTreeDto>();
    }
}